#!/bin/bash

# MySQL MCP Server 自动安装脚本
# 支持 Trae AI, Cursor, VS Code 等IDE

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目信息
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHON_PATH="$PROJECT_ROOT/venv/bin/python3"
SERVER_SCRIPT="$PROJECT_ROOT/src/mysql_mcp_server/main.py"

echo -e "${BLUE}🚀 MySQL MCP Server 自动安装程序${NC}"
echo "=================================================="

# 检查Python环境
check_python_env() {
    echo -e "${YELLOW}📋 检查Python环境...${NC}"
    
    if [ ! -f "$PYTHON_PATH" ]; then
        echo -e "${RED}❌ 未找到虚拟环境，请先运行: python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt${NC}"
        exit 1
    fi
    
    if [ ! -f "$SERVER_SCRIPT" ]; then
        echo -e "${RED}❌ 未找到MCP服务器脚本: $SERVER_SCRIPT${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✅ Python环境检查通过${NC}"
}

# 检测IDE类型
detect_ide() {
    echo -e "${YELLOW}🔍 检测IDE类型...${NC}"
    
    # 检测Trae AI
    if [ -d "$HOME/.trae" ] || [ -d "$HOME/.trae-cn" ] || [ -d "$HOME/.trae-aicc" ]; then
        echo -e "${GREEN}✅ 检测到 Trae AI${NC}"
        return 0
    fi
    
    # 检测Cursor
    if [ -d "$HOME/.cursor" ] || command -v cursor >/dev/null 2>&1; then
        echo -e "${GREEN}✅ 检测到 Cursor${NC}"
        return 1
    fi
    
    # 检测VS Code
    if [ -d "$HOME/.vscode" ] || command -v code >/dev/null 2>&1; then
        echo -e "${GREEN}✅ 检测到 VS Code${NC}"
        return 2
    fi
    
    echo -e "${YELLOW}⚠️  未检测到支持的IDE，将提供通用配置${NC}"
    return 3
}

# 为Trae AI配置MCP
configure_trae() {
    echo -e "${YELLOW}⚙️  配置Trae AI MCP服务器...${NC}"
    
    # 查找Trae配置目录
    TRAE_CONFIG_DIR=""
    for dir in "$HOME/.trae" "$HOME/.trae-cn" "$HOME/.trae-aicc"; do
        if [ -d "$dir" ]; then
            TRAE_CONFIG_DIR="$dir"
            break
        fi
    done
    
    if [ -z "$TRAE_CONFIG_DIR" ]; then
        echo -e "${RED}❌ 未找到Trae配置目录${NC}"
        return 1
    fi
    
    CONFIG_FILE="$TRAE_CONFIG_DIR/mcp_servers.json"
    
    # 创建MCP配置
    cat > "$CONFIG_FILE" << EOF
{
  "mcpServers": {
    "mysql-mcp-server": {
      "command": "$PYTHON_PATH",
      "args": ["$SERVER_SCRIPT"],
      "cwd": "$PROJECT_ROOT",
      "env": {
        "PYTHONPATH": "$PROJECT_ROOT/src"
      }
    }
  }
}
EOF
    
    echo -e "${GREEN}✅ Trae AI配置完成: $CONFIG_FILE${NC}"
}

# 为Cursor配置MCP
configure_cursor() {
    echo -e "${YELLOW}⚙️  配置Cursor MCP服务器...${NC}"
    
    CONFIG_DIR="$HOME/.cursor"
    CONFIG_FILE="$CONFIG_DIR/mcp_servers.json"
    
    mkdir -p "$CONFIG_DIR"
    
    cat > "$CONFIG_FILE" << EOF
{
  "mcpServers": {
    "mysql-mcp-server": {
      "command": "$PYTHON_PATH",
      "args": ["$SERVER_SCRIPT"],
      "cwd": "$PROJECT_ROOT",
      "env": {
        "PYTHONPATH": "$PROJECT_ROOT/src"
      }
    }
  }
}
EOF
    
    echo -e "${GREEN}✅ Cursor配置完成: $CONFIG_FILE${NC}"
}

# 为VS Code配置MCP
configure_vscode() {
    echo -e "${YELLOW}⚙️  配置VS Code MCP服务器...${NC}"
    
    CONFIG_DIR="$HOME/.vscode"
    CONFIG_FILE="$CONFIG_DIR/mcp_servers.json"
    
    mkdir -p "$CONFIG_DIR"
    
    cat > "$CONFIG_FILE" << EOF
{
  "mcpServers": {
    "mysql-mcp-server": {
      "command": "$PYTHON_PATH",
      "args": ["$SERVER_SCRIPT"],
      "cwd": "$PROJECT_ROOT",
      "env": {
        "PYTHONPATH": "$PROJECT_ROOT/src"
      }
    }
  }
}
EOF
    
    echo -e "${GREEN}✅ VS Code配置完成: $CONFIG_FILE${NC}"
}

# 提供通用配置
provide_generic_config() {
    echo -e "${YELLOW}📝 生成通用MCP配置...${NC}"
    
    CONFIG_FILE="$PROJECT_ROOT/mcp_config.json"
    
    cat > "$CONFIG_FILE" << EOF
{
  "mcpServers": {
    "mysql-mcp-server": {
      "command": "$PYTHON_PATH",
      "args": ["$SERVER_SCRIPT"],
      "cwd": "$PROJECT_ROOT",
      "env": {
        "PYTHONPATH": "$PROJECT_ROOT/src"
      }
    }
  }
}
EOF
    
    echo -e "${GREEN}✅ 通用配置已生成: $CONFIG_FILE${NC}"
    echo -e "${BLUE}请将此配置添加到您的IDE的MCP配置文件中${NC}"
}

# 验证配置
verify_config() {
    echo -e "${YELLOW}🔧 验证MCP服务器配置...${NC}"
    
    # 测试Python模块导入
    if ! "$PYTHON_PATH" -c "import src.mysql_mcp_server.main; print('✅ 模块导入成功')" 2>/dev/null; then
        echo -e "${RED}❌ Python模块导入失败${NC}"
        return 1
    fi
    
    # 测试服务器启动（快速测试）
    timeout 5s "$PYTHON_PATH" "$SERVER_SCRIPT" --help >/dev/null 2>&1 || true
    
    echo -e "${GREEN}✅ 配置验证通过${NC}"
}

# 主函数
main() {
    echo -e "${BLUE}开始安装过程...${NC}"
    
    # 检查环境
    check_python_env
    
    # 检测IDE并配置
    detect_ide
    ide_type=$?
    
    case $ide_type in
        0) configure_trae ;;
        1) configure_cursor ;;
        2) configure_vscode ;;
        *) provide_generic_config ;;
    esac
    
    # 验证配置
    verify_config
    
    echo ""
    echo -e "${GREEN}🎉 安装完成！${NC}"
    echo "=================================================="
    echo -e "${BLUE}下一步操作：${NC}"
    echo "1. 重启您的IDE"
    echo "2. 在IDE中查找MCP或插件设置"
    echo "3. 确认mysql-mcp-server已连接"
    echo ""
    echo -e "${YELLOW}如果遇到问题，请运行验证脚本：${NC}"
    echo "  ./verify_mcp.sh"
    echo ""
    echo -e "${BLUE}配置文件位置：${NC}"
    case $ide_type in
        0) echo "  Trae AI: $(find $HOME/.trae* -name "mcp_servers.json" 2>/dev/null | head -1)" ;;
        1) echo "  Cursor: $HOME/.cursor/mcp_servers.json" ;;
        2) echo "  VS Code: $HOME/.vscode/mcp_servers.json" ;;
        *) echo "  通用配置: $PROJECT_ROOT/mcp_config.json" ;;
    esac
}

# 运行主函数
main "$@"